/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import me.zhengjie.modules.cspimp.psp.domain.Chemicla;
import me.zhengjie.modules.cspimp.psp.domain.ChemiclaStockIn;
import me.zhengjie.modules.cspimp.psp.repository.ChemiclaRepository;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.ChemiclaStockInRepository;
import me.zhengjie.modules.cspimp.psp.service.ChemiclaStockInService;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaStockInDto;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaStockInQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.ChemiclaStockInMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-30
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ChemiclaStockInServiceImpl implements ChemiclaStockInService {

    private final ChemiclaStockInRepository chemiclaStockInRepository;
    private final ChemiclaStockInMapper chemiclaStockInMapper;
    private final ChemiclaRepository chemiclaRepository;
    private final UserRepository userRepository;

    @Override
    public Map<String, Object> queryAll(ChemiclaStockInQueryCriteria criteria, Pageable pageable) {
        List<ChemiclaStockIn> page = chemiclaStockInRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<ChemiclaStockInDto> chemiclaStockInList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page)) {
            for (ChemiclaStockIn chemiclaStockIn : page) {
                ChemiclaStockInDto chemiclaStockInDto = new ChemiclaStockInDto();
                BeanUtils.copyProperties(chemiclaStockIn, chemiclaStockInDto);
                User user = userRepository.findById(chemiclaStockIn.getAuditId()).get();
                if (null != user) {
                    chemiclaStockInDto.setUsername(user.getUsername());
                }
                chemiclaStockInList.add(chemiclaStockInDto);
            }
        }
        return PageUtil.toPage(PageUtil.listPage(chemiclaStockInList, pageable));
    }

    @Override
    public List<ChemiclaStockInDto> queryAll(ChemiclaStockInQueryCriteria criteria) {
        return chemiclaStockInMapper.toDto(chemiclaStockInRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public ChemiclaStockInDto findById(Long id) {
        ChemiclaStockIn chemiclaStockIn = chemiclaStockInRepository.findById(id).orElseGet(ChemiclaStockIn::new);
        ValidationUtil.isNull(chemiclaStockIn.getId(), "ChemiclaStockIn", "id", id);
        User user = userRepository.findById(chemiclaStockIn.getAuditId()).get();
        ChemiclaStockInDto chemiclaStockInDto = new ChemiclaStockInDto();
        BeanUtils.copyProperties(chemiclaStockIn, chemiclaStockInDto);
        if (null != user) {
            chemiclaStockInDto.setUsername(user.getUsername());

        }
        return chemiclaStockInDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChemiclaStockInDto create(ChemiclaStockIn resources) {
        //入库量相加
        Chemicla chemicla = chemiclaRepository.findById(resources.getChemiclaId()).get();
        chemicla.setStockCount(chemicla.getStockCount() + resources.getStockInCount());
        chemiclaRepository.save(chemicla);
        resources.setCid(0l);
        return chemiclaStockInMapper.toDto(chemiclaStockInRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ChemiclaStockIn resources) {
        ChemiclaStockIn chemiclaStockIn = chemiclaStockInRepository.findById(resources.getId()).orElseGet(ChemiclaStockIn::new);
        ValidationUtil.isNull(chemiclaStockIn.getId(), "ChemiclaStockIn", "id", resources.getId());
        chemiclaStockIn.copy(resources);
        chemiclaStockInRepository.save(chemiclaStockIn);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            chemiclaStockInRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ChemiclaStockInDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ChemiclaStockInDto chemiclaStockIn : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建者", chemiclaStockIn.getCreateBy());
            map.put("更新者", chemiclaStockIn.getUpdateBy());
            map.put("创建日期", chemiclaStockIn.getCreateTime());
            map.put("更新时间", chemiclaStockIn.getUpdateTime());
            map.put("入库量", chemiclaStockIn.getStockInCount());
            map.put("审核人", chemiclaStockIn.getAuditId());
            map.put("化学品id", chemiclaStockIn.getChemiclaId());
            map.put("当前库存量", chemiclaStockIn.getCurrentStockCount());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}